package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.controllerApi.CategoryControllerApi;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author kcs
 * @date 2021/11/24
 * @TIME:11:28
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController implements CategoryControllerApi {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R add(@RequestBody Category category){

        categoryService.save(category);

        return R.success("添加成功");
    }

    /**
     * 分页查询分类信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize){
        //数据校验

        //设置分页条件
        IPage<Category> pageInfo = new Page<>(page,pageSize);
        //添加排序条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据id删除分类信息
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Long id){
        log.info("删除分类，id为：{}",id);
        categoryService.delete(id);
        return R.success("分类信息删除成功");
    }

    /**
     * 查询分类信息
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R list(Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null,Category::getType,type);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
